import 'dart:async';
import 'dart:convert';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jicaimao_flutter/entity/loginbean.dart';
import 'package:jicaimao_flutter/event/login_event.dart';
import 'package:jicaimao_flutter/utils/api_address.dart';
import 'package:jicaimao_flutter/utils/event_bus.dart';
import 'package:jicaimao_flutter/utils/http_utils.dart';
import 'package:jicaimao_flutter/utils/sp_key.dart';
import 'package:jicaimao_flutter/utils/sp_utils.dart';
import 'package:jicaimao_flutter/views/mine/register_page.dart';
import 'package:jicaimao_flutter/views/web_page.dart';
import 'package:jicaimao_flutter/widget/app_bar.dart';

class QuickLoginPage extends StatefulWidget {
  @override
  _QuickLoginPageState createState() => _QuickLoginPageState();
}

class _QuickLoginPageState extends State<QuickLoginPage> {
  bool isGologin = false;
  bool isClearshow = false;
  bool isClickGetCode = false;
  bool isCheck = false;
  int IsOldUser = 3;
  bool isShowXieyi = false;
  final phone_controller = TextEditingController();
  final code_controller = TextEditingController();
  EventBus eventBus= new EventBus();
  StreamSubscription listen;
  _QuickLoginPageState(){
     listen =  eventBus.on<LoginEvent>().listen((event) {
      // All events are of type UserLoggedInEvent (or subtypes of it).
      if(event.loginComplete==1){
        Navigator.pop(context);
      }
    });
  }


  /// 倒计时的秒数，默认60秒。
  final int countdown = 60;

  /// 倒计时的计时器。
  Timer _timer;

  /// 当前倒计时的秒数。
  int _seconds;

  /// 当前墨水瓶（`InkWell`）的文本。
  String _verifyStr = '获取验证码';

  _login() {
    if (!isGologin) {
      return;
    }
    String pNum = phone_controller.text;
    String ver = code_controller.text;
    if (pNum.isEmpty) {
      showToast( "请输入手机号码");
      return;
    }
    if (!RegexUtil.isMobileExact(pNum)) {
      showToast( "手机号格式不正确");
      return;
    }
    if (ver.isEmpty) {
      showToast( "请输入验证码");
      return;
    }
    if (IsOldUser == 0) {
      if (!isCheck) {
        showToast( "请选择同意用户协议");
        return;
      }
    }
    isGologin = false;
    _loadDataLogin(pNum, ver);
  }

  _loadDataLogin(String phone, String verificationCode) async {
    var data = {
      'terminal': "2",
      "mobile": phone,
      "verificationCode": verificationCode
    };
    var respone = await HttpUtil().post(NetAddress.login, data: data);
    Loginbean loginBean = Loginbean.fromJson(json.decode(respone));
    showToast( loginBean.msg);
    if (loginBean.code == "200") {
      String userId = loginBean.result.userId;
      String serFlag = loginBean.result.serFlag;
      SpUtils.putString(SpKey.SER_FLAG, serFlag);
      SpUtils.putString(SpKey.KEY_USER_ID, userId);

      eventBus.fire(new LoginEvent(1));
    }
  }

  /**
   * 获取验证码
   */
  _getCode() {


    String pNum2 = phone_controller.text;
    isClickGetCode = true;
    if (pNum2.isEmpty) {
      showToast( "请输入手机号码");
      return;
    }
    if (!RegexUtil.isMobileExact(pNum2)) {
      showToast( "手机号格式不正确");
      return;
    }
    print("获取验证码");
    sendCode(pNum2);
  }

  /**
   * 请求验证码
   */
  sendCode(String phone) async {
    var data = {
      'codeType': "7",
      "mobile": phone,
    };
    var respone = await HttpUtil().post(NetAddress.getCode, data: data);
    print(respone);
    Loginbean loginBean = Loginbean.fromJson(json.decode(respone));
    showToast( loginBean.msg);
    if (loginBean.code == "200") {
      if (loginBean.result.isOldUser == 1) {
        IsOldUser = 1;
      } else {
        IsOldUser = 0;
      }

      countDown();
    } else {}

    setState(() {
      print("IsOldUser:::" + IsOldUser.toString());
      isShowXieyi = IsOldUser == 0;
    });
  }

  /**
   * 开启倒计时
   */
  countDown() {
    _startTimer();
    _verifyStr = '${_seconds}s';
    setState(() {});
  }

  /// 启动倒计时的计时器。
  void _startTimer() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_seconds == 0) {
        _cancelTimer();
        _seconds = countdown;
//            inkWellStyle = _availableStyle;
        setState(() {});
        return;
      }
      _seconds--;
      _verifyStr = '${_seconds}s';
      setState(() {});
      if (_seconds == 0) {
        _verifyStr = '重新获取';
      }
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  setBtnState(text) {
    String pNum = phone_controller.text;
    String ver = code_controller.text;

    if (pNum.isNotEmpty && RegexUtil.isMobileExact(pNum) && ver.isNotEmpty) {
      setState(() {
        isGologin = true;
      });
    } else {
      setState(() {
        isGologin = false;
      });
    }
  }

  _inputPhone() {
    return Container(
        height: 40,
        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
        margin: EdgeInsets.fromLTRB(0, 40, 0, 0),
        color: Color(0xfff7f7f7),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: TextField(
                onChanged: (text) {
                  setBtnState(text);
                },
                controller: phone_controller,
                inputFormatters: [LengthLimitingTextInputFormatter(11)],
                maxLength: 11,
                maxLines: 1,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                    hasFloatingPlaceholder: false,
                    counterText: '',
                    border: InputBorder.none,
                    hintText: '请输入手机号',
                    disabledBorder: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none),
                style: TextStyle(
                  color: Color(0xff666666),
                  fontSize: 16.0,
                ),
              ),
            ),
            GestureDetector(
              child: Container(
                width: 40,
                height: 40,
                padding: EdgeInsets.fromLTRB(20, 10, 0, 10),
                child: Image.asset(isClearshow ? 'images/icon_error.png' : ''),
              ),
              onTap: () {
                phone_controller.clear();
                setState(() {
                  isClearshow = !isClearshow;
                });
              },
            )
          ],
        ));
  }

  _inputCode() {
    return Container(
      height: 40,
      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
      color: Color(0xfff7f7f7),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: TextField(
              onChanged: setBtnState,
              controller: code_controller,
              inputFormatters: [LengthLimitingTextInputFormatter(11)],
              maxLength: 11,
              maxLines: 1,
              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                  hasFloatingPlaceholder: false,
                  counterText: '',
                  border: InputBorder.none,
                  hintText: '请输入验证码',
                  disabledBorder: InputBorder.none,
                  enabledBorder: InputBorder.none,
                  focusedBorder: InputBorder.none),
              style: TextStyle(
                color: Color(0xff666666),
                fontSize: 16.0,
              ),
            ),
          ),
          InkWell(
            child: Text(
              '$_verifyStr',
              style: TextStyle(color: Color(0xff6aa9ff)),
            ),
            onTap: _seconds == countdown ? _getCode : null,
          )
        ],
      ),
    );
  }

  ///协议和条款
  _xieyi() {
    return Container(
      child: Row(
        children: <Widget>[
          GestureDetector(
            onTap: () {
              setState(() {
                isCheck = !isCheck;
              });
            },
            child: Container(
              color: Color(0xfffefefe),
              padding: EdgeInsets.only(top: 10, bottom: 10, right: 5, left: 5),
              child: Image.asset(
                isCheck ? "images/icon_check.png" : "images/icon_uncheck.png",
                width: 15,
                height: 15,
              ),
            ),
          ),
          Text("我已经阅读并同意"),
          GestureDetector(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          WebPage("集财猫注册及服务协议", NetAddress.registrationAgreement)));
            },
            child: Text(
              "《协议》",
              style: TextStyle(color: Color(0xffad5afe)),
            ),
          ),
          Text("和"),
          GestureDetector(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          WebPage("用户隐私条款", NetAddress.privacyClause)));
            },
            child: Text("《隐私条款》", style: TextStyle(color: Color(0xffad5afe))),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarNormal("快速登录"),
      body: new SingleChildScrollView(
        child: new ConstrainedBox(
          constraints: new BoxConstraints(
            minHeight: 120.0,
          ),
          child: Container(
            margin: EdgeInsets.fromLTRB(20, 0, 20, 0),
            child: Column(
              children: <Widget>[
                //logo
                Container(
                  margin: EdgeInsets.only(top: 40),
                  height: 70,
                  child: Center(
                    child: Image.asset(
                      'images/icon.png',
                      width: 70,
                      height: 70,
                    ),
                  ),
                ),

                ///输入框
                _inputPhone(),
                Container(
                  height: 1,
                  color: Color(0xffDCDCDC),
                ),
                _inputCode(),
                GestureDetector(
                  onTap: () {
//                    Navigator.push(
//                      context,
//                      MaterialPageRoute(
//                          builder: (context) => ForgetpasswordPage()),
//                    );
                  },
                  child: Container(
                      alignment: Alignment.centerRight,
                      padding: EdgeInsets.only(top: 10, bottom: 10),
                      child: Text(
                        "",
                        style: TextStyle(color: Color(0xffad5afe)),
                      )),
                ),

                GestureDetector(
                  onTap: _login,
                  child: Container(
                      margin: EdgeInsets.only(top: 40),
                      decoration: new BoxDecoration(
                          color:
                              isGologin ? Color(0xffad5afe) : Color(0xffD4d4d4),
                          borderRadius: BorderRadius.circular(3.0)),
                      alignment: Alignment.center,
                      height: 40,
                      width: double.infinity,
                      child: Text(
                        "登录",
                        style: TextStyle(color: Colors.white),
                      )),
                ),
                Container(
                  width: double.infinity,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      GestureDetector(
                        onTap: () {
                          ///账号密码登录
                          Navigator.pop(context);
                        },
                        child: Container(
                          color: Colors.white,
                          padding: EdgeInsets.only(top: 15, bottom: 15),
                          child: Text(
                            "账号密码登录",
                            style: TextStyle(fontSize: 14),
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          ///注册新账号
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => RegisterPage()),
                          );
                        },
                        child: Container(
                          color: Colors.white,
                          padding: EdgeInsets.only(top: 15, bottom: 15),
                          child: Text("注册新账号", style: TextStyle(fontSize: 14)),
                        ),
                      ),
                    ],
                  ),
                ),

                isShowXieyi ? _xieyi() : Container(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _cancelTimer();
    listen?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _seconds = countdown;

  }

  void showToast(String tipMsg) {
    Fluttertoast.showToast(
        msg: tipMsg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1,
        backgroundColor: Colors.black87,
        textColor: Colors.white,
        fontSize: 16.0);
  }
}
